import 'package:chat_ai/src/components/session_config_widget.dart';
import 'package:chat_ai/src/models/session_model.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SessionConfig extends StatefulWidget {
  const SessionConfig({super.key, required this.sessionModel});
  final SessionModel sessionModel;

  @override
  State<StatefulWidget> createState() => _SessionConfigState();
}

class _SessionConfigState extends State<SessionConfig> {
  final _formKey = GlobalKey<FormState>();
  final _nameInputController = TextEditingController();
  final _hostInputControllers = List.generate(
    4,
    (index) => TextEditingController(),
  );
  final _portInputController = TextEditingController();
  late final SharedPreferences _prefs;

  @override
  void initState() {
    super.initState();
    _nameInputController.text = widget.sessionModel.name;
    for (int index in Iterable.generate(4)) {
      _hostInputControllers[index].text =
          widget.sessionModel.host.split(".")[index];
    }
    _portInputController.text = widget.sessionModel.port.toString();
    _initState();
  }

  void _initState() async {
    _prefs = await SharedPreferences.getInstance();
  }

  @override
  void dispose() {
    super.dispose();
    _nameInputController.dispose();
    for (int iter in Iterable.generate(4)) {
      _hostInputControllers[iter].dispose();
    }
    _portInputController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("会话配置"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: SessionConfigWidget(
          formKey: _formKey,
          nameInputController: _nameInputController,
          hostInputControllers: _hostInputControllers,
          portInputController: _portInputController,
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 4),
                child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor:
                        WidgetStateProperty.all<Color>(Colors.green.shade400),
                  ),
                  child: const Text("保存"),
                  onPressed: () {
                    if (!_formKey.currentState!.validate()) return;
                    List<String> sessionNames =
                        _prefs.getStringList("sessionNames") ?? [];
                    if (_nameInputController.text != widget.sessionModel.name &&
                        sessionNames.contains(_nameInputController.text)) {
                      showDialog(
                        context: context,
                        builder: (context) => const AlertDialog(
                          title: Text("该名称已被占用"),
                        ),
                      );
                      // const AlertDialog(
                      //   title: Text("该名称已存在"),
                      //   content: Text("请换个名称"),
                      // );
                      return;
                    }
                    sessionNames[
                            sessionNames.indexOf(widget.sessionModel.name)] =
                        _nameInputController.text;
                    _prefs.setStringList("sessionNames", sessionNames);
                    _prefs.remove("${widget.sessionModel.name}.host");
                    _prefs.setString(
                      "${_nameInputController.text}.host",
                      _hostInputControllers
                          .map((controller) => controller.text)
                          .join("."),
                    );
                    _prefs.remove("${widget.sessionModel.name}.port");
                    _prefs.setInt(
                      "${_nameInputController.text}.port",
                      int.parse(_portInputController.text),
                    );
                    Navigator.pop(context);
                  },
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 4),
                child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor:
                        WidgetStateProperty.all<Color>(Colors.red.shade400),
                  ),
                  child: const Text("删除"),
                  onPressed: () {
                    List<String> sessionNames =
                        _prefs.getStringList("sessionNames")!;
                    sessionNames.remove(widget.sessionModel.name);
                    _prefs.setStringList("sessionNames", sessionNames);
                    _prefs.remove("${widget.sessionModel.name}.host");
                    _prefs.remove("${widget.sessionModel.name}.port");
                    Navigator.pop(context);
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
